<template>
  <el-dialog
    :title="titleMap[mode]"
    :visible.sync="visible"
    width="600px"
    destroy-on-close
    :close-on-click-modal="false"
    @closed="$emit('closed')"
  >
    <el-form
      :model="form"
      :rules="rules"
      :disabled="mode == 'show'"
      ref="dialogForm"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="表单名称" prop="title">
        <el-input v-model="form.title" clearable></el-input>
      </el-form-item>

      <el-form-item label="表名" prop="table">
        <el-input
          v-model="form.table"
          clearable
          placeholder="只允许小写字母、数字、下划线，且不能以数字开头"
        ></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio v-model="form.status" label="1">启用</el-radio>
        <el-radio v-model="form.status" label="2">禁用</el-radio>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false" size="small">取 消</el-button>
      <el-button
        v-if="mode != 'show'"
        type="primary"
        :loading="isSaveing"
        @click="submit()"
        size="small"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>

<script>
export default {
  emits: ["success", "closed"],
  data() {
    return {
      mode: "add",
      titleMap: {
        add: "新增表单",
        edit: "编辑表单",
      },
      visible: false,
      isSaveing: false,
      //表单数据
      form: {
        id: "",
        title: "",
        status: "1",
        table: "",
      },
      //验证规则
      rules: {
        title: [
          { required: true, message: "请输入表单名称", trigger: "change" },
        ],
        status: [{ required: true, message: "请选择状态" }],
        table: [{ required: true, message: "请输入表名" }],
      },
    };
  },
  created() {},
  methods: {
    //显示
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;

          let res;
          if (this.mode == "add") {
            res = await this.$api.form.add.post(this.form);
          } else {
            res = await this.$api.form.edit.post(this.form);
          }

          this.isSaveing = false;
          if (res.code == 0) {
            this.$emit("success", this.form, this.mode);
            this.visible = false;
            this.$message.success(res.msg);
          } else {
            this.$alert(res.msg, "提示", { type: "error" });
          }
        }
      });
    },
    //表单注入数据
    setData(data) {
      this.form.id = data.id;
      this.form.title = data.title;
      this.form.status = String(data.status);
      this.form.table = data.table;
    },
  },
};
</script>

<style>
</style>
